package com.witframework.dynoengine.render;



import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.witframework.core.ApplicationProperties;
import com.witframework.dynoengine.render.MiniTemplator.TemplateSpecification;
import com.witframework.util.ClassLoaderUtil;


public class TempleteFactory {
	static String TEMPLATE_PATH="/com/witframework/dynoengine/templete/";
	private HashMap<String, MiniTemplator> cache;
	static TempleteFactory instance;
	static{
		instance=new TempleteFactory();
	}
	public static TempleteFactory getInstance(){		
		return instance;
	}
	private TempleteFactory() {
		cache = new HashMap<String, MiniTemplator>();
	}
	public synchronized MiniTemplator getMiniTemplator(String templateName,String...condition){
		StringUtils.isEmpty(templateName);
		MiniTemplator mt = cache.get(templateName);
		if (mt == null||Boolean.parseBoolean(ApplicationProperties.getProperty("template_reload","true"))) {
			try {
				TemplateSpecification ts=new TemplateSpecification();
				ts.templateFileName=templateName;
				ts.templateText=readTemplateContent(templateName);
				ts.charset=Charset.forName("utf-8");				
				Set con=new HashSet();
				for(String flag:condition)
					con.add(flag);
				ts.conditionFlags=con;
				mt = new MiniTemplator(ts);			
				cache.put(templateName, mt);
			} catch (Exception e) {
				String msg="获取MiniTemplator实例出错";
				throw new MiniTemplatorCreateException(e.getMessage(),e);
			}
		}
		return mt.cloneReset();
	}
	
	public String readTemplateContent(String template){
		InputStream templateInputStream= ClassLoaderUtil.getStreamByExtendResource(TEMPLATE_PATH+template);		
		byte[] text;
		try {
			text = new byte[templateInputStream.available()];
			templateInputStream.read(text);
		}catch (Exception e) {
				String msg="出错";
				if(templateInputStream==null)
					msg+=",无法读取模板文件："+TEMPLATE_PATH+template;
				throw new MiniTemplatorCreateException(msg,e);
		}
		try {
			return new String(text,"utf-8");
		} catch (UnsupportedEncodingException e) {
			return new String(text,Charset.defaultCharset());
		}
	}
	/**
	 * Clears the cache.
	 */
	public synchronized void clear() {
		cache.clear();
	}
}
